const mongoose = require('mongoose');
const faker = require('faker');

// 连接到 MongoDB
mongoose.connect('mongodb://localhost:27017/student-grade-management', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// 导入模型
const Student = require('./models/Student');
const Grade = require('./models/Grade');
const User = require('./models/User');

// 生成随机学生数据
function generateStudents(count) {
  const students = [];
  for (let i = 1; i <= count; i++) {
    const studentId = `2024${i.toString().padStart(3, '0')}`;
    const gender = faker.random.arrayElement(['男', '女']);
    students.push({
      studentId,
      name: faker.name.findName(),
      gender,
      age: faker.datatype.number({ min: 15, max: 20 }),
      class: `Class ${faker.datatype.number({ min: 1, max: 6 })}`,
      contact: faker.phone.phoneNumber(),
      totalScore: 0,
    });
  }
  return students;
}

// 生成随机成绩数据
function generateGrades(students, subjects, semesters, perStudent) {
  const grades = [];
  students.forEach(student => {
    for (let i = 0; i < perStudent; i++) {
      const subject = faker.random.arrayElement(subjects);
      const semester = faker.random.arrayElement(semesters);
      grades.push({
        studentId: student.studentId,
        subject,
        score: faker.datatype.number({ min: 0, max: 100 }),
        semester,
      });
    }
  });
  return grades;
}

// 计算并更新总分
async function updateTotalScores() {
  const students = await Student.find();
  for (const student of students) {
    const grades = await Grade.find({ studentId: student.studentId });
    const totalScore = grades.reduce((sum, grade) => sum + grade.score, 0);
    student.totalScore = totalScore;
    await student.save();
  }
  console.log('Total scores updated');
}

// 主函数
async function seedDatabase() {
  try {
    // 清空现有数据
    await Student.deleteMany();
    await Grade.deleteMany();
    await User.deleteMany();
    console.log('Database cleared');

    // 定义常量
    const SUBJECTS = ['数学', '语文', '英语', '物理', '化学', '生物'];
    const SEMESTERS = ['第一学期', '第二学期'];
    const STUDENT_COUNT = 20;
    const GRADES_PER_STUDENT = 8;

    // 生成并保存学生数据
    const students = generateStudents(STUDENT_COUNT);
    await Student.insertMany(students);
    console.log(`${students.length} students created`);

    // 生成并保存成绩数据
    const grades = generateGrades(students, SUBJECTS, SEMESTERS, GRADES_PER_STUDENT);
    await Grade.insertMany(grades);
    console.log(`${grades.length} grades created`);

    // 更新总分
    await updateTotalScores();

    // 生成并保存用户数据
    const users = [
      {
        username: 'teacher1',
        password: '123456',
        role: 'teacher'
      }
    ];

    // 为每个学生创建对应的用户账号
    students.forEach((student, index) => {
      users.push({
        username: `student${index + 1}`,
        password: '123456',
        role: 'user',
        studentId: student.studentId
      });
    });

    await User.insertMany(users);
    console.log(`${users.length} users created`);

    console.log('Database seeded successfully');
  } catch (error) {
    console.error('Error seeding database:', error);
  } finally {
    mongoose.disconnect();
  }
}

// 执行脚本
seedDatabase();

module.exports = {};  
